//
//  RecordDownloader.m
//  CET
//
//  Created by Kai on 8/27/10.
//  Copyright 2010 NONAME STUDIO. All rights reserved.
//

#import "RecordDownloader.h"
#import "NSString+URLEncodeString.h"
#import "CETRecord.h"

@implementation RecordDownloader

@synthesize delegate;
@synthesize cetRecord, indexPathInTableView;
@synthesize activeDownload, recordConnection;
@synthesize didFinishLoading;

- (id)initWithAdmissionCard:(NSString *)card {
	
	if ((self = [super init])) {
		
		cetRecord = [[CETRecord alloc] init];
		cetRecord.admissionCard = card;
	}
	
	return self;
}

- (void)dealloc {
	
	[cetRecord release];
    [indexPathInTableView release];
    
    [activeDownload release];

    [recordConnection cancel];
    [recordConnection release];
	
	[super dealloc];
}

- (void)startDownload {
	
	// Check cache.
	NSString *cache = [[NSUserDefaults standardUserDefaults] objectForKey:cetRecord.admissionCard];
	if (cache) {
		
		//NSLog(@"USERDEFAULTS: %@", cache);
		
		NSArray *array = [cache componentsSeparatedByString:@","];
		
		if ([array count] == 7) {
			
			@try {
				cetRecord.name = [array objectAtIndex:6];
				cetRecord.schoolName = [array objectAtIndex:5];
				cetRecord.totalScore = [[array objectAtIndex:4] intValue];
				cetRecord.listening = [[array objectAtIndex:0] intValue];
				cetRecord.reading = [[array objectAtIndex:1] intValue];
				cetRecord.cloze = [[array objectAtIndex:2] intValue];
				cetRecord.writing = [[array objectAtIndex:3] intValue];
								
				didFinishLoading = YES;
				
				// call our delegate and tell it that our icon is ready for display
				[delegate recordDidDownload:self.indexPathInTableView];
				
				return;
			}
			@catch (NSException * e) {
				NSLog(@"%@", e);
			}
			@finally {
				
			}
		}
	}
	
	// If cache is nil, download it.
    self.activeDownload = [NSMutableData data];
	
	NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"http://cet.99sushe.com/getscore.html"] 
															cachePolicy:NSURLRequestUseProtocolCachePolicy
														timeoutInterval:10.0f];
	
	[request setHTTPMethod:@"POST"];
	[request setHTTPBody:[[NSString stringWithFormat:@"id=%@&vc=novcversion", cetRecord.admissionCard] dataUsingEncoding:NSUTF8StringEncoding]];
	[request setValue:@"http://cet.99sushe.com" forHTTPHeaderField:@"Referer"];
	
	// alloc+init and start an NSURLConnection; release on completion/failure
    NSURLConnection *conn = [[NSURLConnection alloc] initWithRequest:request delegate:self];
	
    self.recordConnection = conn;
    [conn release];
		
	NSLog(@"Starting...");
}

- (void)cancelDownload {
	
    [self.recordConnection cancel];
    self.recordConnection = nil;
    self.activeDownload = nil;
}

#pragma mark -
#pragma mark Download support (NSURLConnectionDelegate)

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
	
    [self.activeDownload appendData:data];
}

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
	
	NSLog(@"Failed -- %@", error);
	
	// Clear the activeDownload property to allow later attempts
    self.activeDownload = nil;
    
    // Release the connection now that it's finished
    self.recordConnection = nil;
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
	
	// Release the connection now that it's finished
    self.recordConnection = nil;
	
	NSStringEncoding enc = CFStringConvertEncodingToNSStringEncoding(kCFStringEncodingGB_18030_2000);
	NSString *string = [[NSString alloc] initWithData:self.activeDownload encoding:enc];
	
	[[NSUserDefaults standardUserDefaults] setObject:string forKey:cetRecord.admissionCard];
	[[NSUserDefaults standardUserDefaults] synchronize];
	
	NSLog(@"Result %@", string);
	
	NSArray *array = [string componentsSeparatedByString:@","];
	
	if ([array count] == 7) {
		
		cetRecord.name = [array objectAtIndex:6];
		//cetRecord.name = [[[array objectAtIndex:6] substringToIndex:1] stringByAppendingString:@"**"];
		cetRecord.schoolName = [array objectAtIndex:5];
		cetRecord.totalScore = [[array objectAtIndex:4] intValue];
		cetRecord.listening = [[array objectAtIndex:0] intValue];
		cetRecord.reading = [[array objectAtIndex:1] intValue];
		cetRecord.cloze = [[array objectAtIndex:2] intValue];
		cetRecord.writing = [[array objectAtIndex:3] intValue];
		
		didFinishLoading = YES;
		
		// call our delegate and tell it that our icon is ready for display
		[delegate recordDidDownload:self.indexPathInTableView];
	} else {
		
		cetRecord.name = @"ERROR";
		
		//[self startDownload];
	}
}


@end
